use serde_json::Value;

use serde_yml;
use std::{fs};
use std::fs::File;
use anyhow::{Result};
use crate::opts::OutputFormat;

pub fn process_csv(input_path: &str, out_path: &str, format: OutputFormat) {
    let reslut = read_file(input_path);

    match reslut {
        Ok(list) => {
            let res = write_file(list, out_path, format);
            println!("{:?}", res.unwrap());
        }
        Err(e) => {
            println!("read file error {}", e);
        }
    }
}


// 写入文件
fn write_file(data: Vec<Value>, path: &str, format: OutputFormat) -> anyhow::Result<String> {
    let content = match format {
        OutputFormat::Json => serde_json::to_string_pretty(&data)?, // to_string_pretty  会换行 ， to_string 不会换行
        OutputFormat::Yml => serde_yml::to_string(&data)?,
    };

    fs::write(path, content).expect("write file error");
    Ok("convet csv success!".to_string())
}

// 读取文件
fn read_file(path: &str) -> Result<Vec<Value>> {
    let file = File::open(path)?;
    let mut list = Vec::new();
    let mut rdr = csv::Reader::from_reader(file);

    let headers = rdr.headers()?.clone();

    for result in rdr.records() {  //
        let record = result?;    //
        let json = headers.iter().zip(record.iter()).collect::<Value>();

        list.push(json);
    };
    Ok(list)
}
